package com.tz.controller;

import com.tz.entity.User;
import com.tz.entity.dto.UserDto;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yejf on 2017/1/17.
 * Bean 验证器的控制器 演示
 */
@Controller
public class BeanValidatorController {

    private static final Logger LOGGER = Logger.getLogger(BeanValidatorController.class);

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(Model model, @Valid User user, BindingResult bindingResult) {
//      public String add(Model model, @Valid UserDto user, BindingResult bindingResult) {
        LOGGER.debug("** 进入控制器的add方法...");
        // 判断是否有不符合规则的数据
        if(bindingResult.hasErrors()) {
            //
            LOGGER.debug("-- 验证没有通过....");
            //添加相关的属性到model中
            model.addAttribute("user", user);
            model.addAttribute("errors", getErrorMap(bindingResult));
            //继续在当前的添加页面
            return "/user/add.jsp";
        }
        //
        LOGGER.debug("-- BeanValidation 验证通过....");
        return "/index.jsp";
    }

    private Object getErrorMap(BindingResult bindingResult) {
        LOGGER.debug("--- 创建一个Map用来存放错误数据...");
        Map<String, String> errorMap = new HashMap<>();
        //迭代整个 bindingResult，把错误域及对应的消息取出来，存放到errorMap中
        for(ObjectError objectError : bindingResult.getAllErrors()) {
            FieldError fieldError = (FieldError)objectError;
            //
            String field = fieldError.getField(); // 获取域
            LOGGER.debug("--- field: "+field);
            String error = fieldError.getDefaultMessage();
            LOGGER.debug("-- message: "+error);
            //
            errorMap.put(field, error);
        }
        //返回
        return errorMap;
    }

}
